import axios from "axios";
import {ElMessage} from "element-plus";
import {debounce} from '@/utils/common'
import router from '@/router'

//创建axios实例
let request = axios.create({
    baseURL: import.meta.env.VITE_SERVE + import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
});

//请求拦截器
request.interceptors.request.use(config => {
    return config;
});
//响应拦截器
request.interceptors.response.use((response) => {
    // 如果是图片接口，直接返回整个 response
    if (response.headers["content-type"] === 'image/png') {
        return response;
    }
    // 统一处理成功响应
    if (response.data?.code === 0) {
        return response.data.data; // 直接返回data部分
    }
    return Promise.reject(new Error(response.data?.message || 'Request failed'));
}, (error) => {
    if (error.code == 'ERR_CANCELED') {
        //拒绝响应
        return Promise.race([]);
    }
    //处理网络错误
    let msg = '';
    let status = error?.response?.status;
    switch (status) {
        case 401:
            msg = "请先登录";
            router.push('/user/login')
            break;
        case 403:
            msg = '无权访问';
            break;
        case 404:
            msg = "请求地址错误";
            break;
        case 500:
            msg = error?.response?.data?.msg ? error?.response?.data?.msg : "服务器出现问题";
            break;
        default:
            msg = "无网络";

    }
    showErrorMessage(msg)
    return Promise.reject(error);
});

const showErrorMessage = debounce((msg : string) => {
    ElMessage({
        type: 'error',
        message: msg
    })
}, 200)
export default request;